package com.wh.wisdomsite.xbox.server.controller.me;

import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.me.entity.CraneStandard;
import com.wh.wisdomsite.xbox.me.service.ICraneStandardService;
import com.wh.wisdomsite.xbox.pojo.me.CraneStandardIn;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.server.util.WrapperUtil;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 起重器械标准配置 控制层
 *
 * @author 蔡道行
 * @version V1.0
 * @package com.wh.wisdomsite.xbox.server.controller.me
 * @date 15:06 2018/8/5
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 */
@Controller
@RequestMapping(value = "/craneStandard")
public class CraneStandardController {

    private static final Log logger = LogFactory.getLog(CraneStandardController.class);


    @Autowired
    private ICraneStandardService iCraneStandardService;

    /**
     * 跳转到起重机标准配置列表页面
     *
     * @return
     */
    @RequiresPermissions("rules:me_craneStandard_page")
    @RequestMapping("index.do")
    public String index() {
        return "/me/craneStandard/craneStandardList";
    }

    /**
     * 获取起重机械标准配置集合
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:me_craneStandard_find")
    @RequestMapping(value = "/craneStandardList.do")
    public void craneStandardList(HttpServletResponse response, CraneStandardIn in) {
        try {
            logger.info("加载起重机械配置数据列表-->>开始");
            //设置分页
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<CraneStandard> page = new Page<CraneStandard>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            WrapperUtil<CraneStandard> ewCraneStandard = new WrapperUtil<CraneStandard>();
            ewCraneStandard.setEntity(new CraneStandard());
            if (StringUtils.isNotEmpty(in.getCsType())) {
                ewCraneStandard.like("csType", in.getCsType());
            }
            if (StringUtils.isNotEmpty(in.getCsVer())) {
                ewCraneStandard.like("csVer", in.getCsVer());
            }
            if (StringUtils.isNotEmpty(in.getBasicType())) {
                ewCraneStandard.like("basicType", in.getBasicType());
            }
            if (in.getCapacity() != null) {
                ewCraneStandard.eq("capacity", in.getCapacity());
            }
            if (in.getTorque() != null) {
                ewCraneStandard.eq("torque", in.getTorque());
            }
            if (in.getMaxRange() != null) {
                ewCraneStandard.eq("maxRange", in.getMaxRange());
            }
            if (in.getMaxWindSpeed() != null) {
                ewCraneStandard.eq("maxWindSpeed", in.getMaxWindSpeed());
            }
            if (in.getLiftHeight() != null) {
                ewCraneStandard.eq("liftHeight", in.getLiftHeight());
            }
            if (in.getSlewingSpeed() != null) {
                ewCraneStandard.eq("slewingSpeed", in.getSlewingSpeed());
            }
            //设置假的公司条件
            if(UserUtils.getCurrentUserParentCompany()!=null) {
                ewCraneStandard.eq("companyId", UserUtils.getCurrentUserParentCompany().getCompanyId());
            }
            ewCraneStandard.orderBy("createDate", true);
            Page<Map<String, Object>> craneStandardPage = iCraneStandardService.getMapsPage(page, ewCraneStandard);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (craneStandardPage.getRecords().size() > 0) {
                for (Map<String, Object> craneStandard : craneStandardPage.getRecords()) {
                    JSONObject object = new JSONObject(craneStandard);
                    object.put("id", craneStandard.get("csId"));
                    if (craneStandard.get("csType") != null) {
                        object.put("csType", new JSONObject(craneStandard.get("csType")));
                    }
                    if (craneStandard.get("basicType") != null) {
                        object.put("basicType", new JSONObject(craneStandard.get("basicType")));
                    }
                    array.put(object);
                }
            }
            json.put("total", craneStandardPage.getTotal());
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载起重机械配置数据列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("加载起重机械配置数据列表-->>Exception" + e.getMessage());
        }
    }


    /**
     * 起重机标准配置详情
     *
     * @param craneStandardIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:me_craneStandard_view")
    @RequestMapping("/craneStandardDesc.do")
    public String craneStandardDesc(CraneStandardIn craneStandardIn, HttpServletRequest request) {
        logger.info("项目详情-->>开始");
        Map<String, Object> craneStandard = iCraneStandardService.getMapById(craneStandardIn.getCsId());
        if(craneStandard.get("createBy") != null){
            craneStandard.put("createBy", UserMapManager.getUserLoginNameInMap(craneStandard.get("createBy").toString()));
        }
        if(craneStandard.get("updateBy") != null){
            craneStandard.put("updateBy", UserMapManager.getUserLoginNameInMap(craneStandard.get("updateBy").toString()));
        }
        request.setAttribute("craneStandard", craneStandard);
        logger.info("项目详情-->>结束");
        return "/me/craneStandard/craneStandardDesc";
    }


    /**
     * 操作起重机标准配置(添加/修改)
     *
     * @param craneStandard
     * @param response
     * @throws Exception
     */
    @RequiresPermissions("rules:me_craneStandard_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(CraneStandard craneStandard, HttpServletResponse response) {
        try {
            //判断方法是否已经存在,存在即更新.否则为添加
            if (StringUtils.isNotEmpty(craneStandard.getCsId())) {
                logger.info("修改起重机标准配置-->>开始");
                craneStandard.setUpdateBy(UserUtils.getCurrentUser().getUsId());
                craneStandard.setUpdateDate(new Date());
                iCraneStandardService.updateById(craneStandard);
                logger.info("修改起重机标准配置-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("起重机标准配置更新成功"));

            } else {
                logger.info("添加起重机标准配置-->>开始");
                craneStandard.setCreateDate(new Date());
                craneStandard.setCompanyId(UserUtils.getCurrentUser().getCompanyId());
                craneStandard.setCreateBy(UserUtils.getCurrentUser().getUsId());
                iCraneStandardService.insert(craneStandard);
                logger.info("添加起重机标准配置-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("起重机标准配置添加成功"));

            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("操作起重机标准配置-->>Exception" + e.getMessage());
        }
    }


    /**
     * 删除起重机标准配置
     *
     * @param id
     * @param response
     */
    @RequiresPermissions("rules:me_craneStandard_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String id, HttpServletResponse response) {
        try {
            logger.info("删除起重机标准配置-->>开始");
            iCraneStandardService.deleteById(id);
            logger.info("删除起重机标准配置-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("起重机标准配置删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除起重机标准配置-->>Exception" + e.getMessage());
        }
    }

    /**
     * 跳转至添加或修改页面
     *
     * @return
     */
    @RequestMapping("/toCraneStandard.do")
    public ModelAndView toAddActivity(String csId, HttpServletRequest request) {
        logger.info("添加修改项目跳转-->>开始");
        if (StringUtils.isNotEmpty(csId)) {
            Map<String, Object> craneStandard = iCraneStandardService.getMapById(csId);
            request.setAttribute("craneStandard", craneStandard);
        }
        logger.info("添加修改项目跳转-->>结束");
        return new ModelAndView("me/craneStandard/craneStandardOption");
    }


    /**
     * 根据当前登陆的用户的公司Id查询起重机械标准配置对象
     * @param response
     */
    @RequestMapping("/getCraneStandardList.do")
    public void getCraneStandardList(HttpServletResponse response) {
        logger.info("添加修改项目跳转-->>开始");
        Integer companyId = UserUtils.getCurrentUser().getCompanyId();
        List<CraneStandard> craneStandards =null;
        if(UserUtils.isSysAdmin()){
            craneStandards = iCraneStandardService.getCraneStandardList(null);
        }else{
            craneStandards = iCraneStandardService.getCraneStandardList(companyId);
        }
        try{
            JSONArray jsonArray = new JSONArray();
            if(craneStandards.size()>0) {
            for (CraneStandard craneStandard:craneStandards ) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", craneStandard.getCsId());
                    jsonObject.put("text", craneStandard.getCsVer());
                    jsonArray.put(jsonObject);
                }
            }
            ResManager.getTextOut(response).print(jsonArray);
        }catch (Exception e){
            e.printStackTrace();
        }
        logger.info("添加修改项目跳转-->>结束");
    }
}

